<?php

namespace app\index\model;

use app\common\ConfigBase;
use app\common\model\ToolModel;
use  think\Db;

class WarehousecountryModel
{
    static public function getList($param, $titles = null, $function = null){
        $db = Db::table('warehouse_country');
        !empty($param['code'])&&$db->where('code', 'in',explodeStr($param['code']));
        !empty($param['retail_company'])&&$db->where('retail_company', $param['retail_company']);
        !empty($param['bs_code'])&&$db->where('bs_code', $param['bs_code']);
        !empty($param['code'])&&$db->where('code', $param['code']);
        !empty($param['receipt_warehouse_id'])&&$db->where('receipt_warehouse_id', $param['receipt_warehouse_id']);
        $db->where('receipt_warehouse_id','in',ConfigBase::getWarehouseCountryPermission());
        $db->order('id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }
    static public function getSKuNum($ids){
        return DB::table('warehouse_country_detail')
            ->where('warehouse_country_id','in',$ids)
            ->group('warehouse_country_id')
            ->column("count(sku) as sku_num","warehouse_country_id");
    }
    static public function getCostList($param, $titles = null, $function = null){
        $db = Db::table('warehouse_country_cost');
        !empty($param['code'])&&$db->where('code', 'in',explodeStr($param['code']));
        !empty($param['receipt_warehouse_id'])&&$db->where('receipt_warehouse_id', $param['receipt_warehouse_id']);
        !empty($param['sku'])&&$db->where('sku', 'in',explodeStr($param['sku']));
        $db->where('receipt_warehouse_id','in',ConfigBase::getWarehouseCountryPermission());
        if (!empty($param['date'])) {
            $date = explode(' - ', $param['date']);
            count($date) == 2 &&
            $db->where('date', '>=', $date[0]) &&
            $db->where('date', '<=', $date[1]);
        }
        $db->order('id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }
    static public function getStockList($param, $titles = null, $function = null){
        $db = Db::table('warehouse_country_stock');
        !empty($param['stock_age'])&&$db->where('stock_age', 'in',explodeStr($param['stock_age']));
        !empty($param['receipt_warehouse_id'])&&$db->where('receipt_warehouse_id', $param['receipt_warehouse_id']);
        !empty($param['sku'])&&$db->where('sku', 'in',explodeStr($param['sku']));
        $db->where('receipt_warehouse_id','in',ConfigBase::getWarehouseCountryPermission());
        $db->order('id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }
    static public function getAdvanceList($param, $titles = null, $function = null){
        $db = Db::table('warehouse_country_advance');
        !empty($param['code'])&&$db->where('code', 'in',explodeStr($param['code']));
        !empty($param['bs_code'])&&$db->where('bs_code', 'in',explodeStr($param['bs_code']));
        !empty($param['receipt_warehouse_id'])&&$db->where('receipt_warehouse_id', $param['receipt_warehouse_id']);
        !empty($param['sku'])&&$db->where('sku', 'in',explodeStr($param['sku']));
        $db->where('receipt_warehouse_id','in',ConfigBase::getWarehouseCountryPermission());
        $db->order('id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }
    //修改库存成本及单价
    static public function getCostSum($param){
       $info=Db::table('warehouse_country_cost')
            ->field("sum(price*surplus) as money")
            ->where(['receipt_warehouse_id'=>$param['receipt_warehouse_id'],'sku'=>$param['sku'],'status'=>1,'surplus'=>['>',0]])
            ->group('receipt_warehouse_id,sku')
            ->find();
       if(empty($info)){
           $data=['cost'=>0,'wam'=>0];
       }else{
           $data=['cost'=>$info['money'],'wam'=>Db::raw("{$info['money']}/physical_stock")];
       }
       $row=Db::table('warehouse_country_stock')
            ->where(['receipt_warehouse_id'=>$param['receipt_warehouse_id'],'sku'=>$param['sku']])
            ->update($data);
       if(!$row){
           return returnArr(500,'修改库存成本失败');
       }
       return returnArr(1);
    }
    static public function getOutList($param, $titles = null, $function = null){
        $db = Db::table('warehouse_country_out');
        !empty($param['code'])&&$db->where('code', 'in',explodeStr($param['code']));
        !empty($param['bs_code'])&&$db->where('bs_code', $param['bs_code']);
        if (!empty($param['date'])) {
            $date = explode(' - ', $param['date']);
            count($date) == 2 &&
            $db->where('date', '>=', $date[0]) &&
            $db->where('date', '<=', $date[1]);
        }
        !empty($param['ship_warehouse_id'])&&$db->where('ship_warehouse_id', $param['ship_warehouse_id']);
        $db->where('ship_warehouse_id','in',ConfigBase::getWarehouseCountryPermission());
        $db->order('id','desc');
        return \app\common\service\ToolService::downOrReturn($db, $param, $titles, $function);
    }
    static public function getSKuNumByOut($ids){
        return DB::table('warehouse_country_out_detail')
            ->where('warehouse_country_out_id','in',$ids)
            ->group('warehouse_country_out_id')
            ->column("count(sku) as sku_num","warehouse_country_out_id");
    }
    //修改库龄
    static public function updateSkuStockAge($param){
        $physical_stock=Db::table('warehouse_country_stock')
            ->where(['receipt_warehouse_id'=>$param['receipt_warehouse_id'],'sku'=>$param['sku']])
            ->value('physical_stock');
        ;
        $arr=Db::table('warehouse_country_cost')
            ->where(['receipt_warehouse_id'=>$param['receipt_warehouse_id'],'sku'=>$param['sku'],'status'=>1,'quantity'=>['>',0]])
            ->select();
        $stock_age=0;
        foreach ($arr as $value){
            $stock_age = $stock_age+round(($value['surplus'] / $physical_stock) * ((time() - strtotime($value['date'])) / 86400), 4); // 库龄保留两位小数
        }
        Db::table('warehouse_country_stock')
            ->where(['receipt_warehouse_id'=>$param['receipt_warehouse_id'],'sku'=>$param['sku']])
            ->update(['stock_age'=>$stock_age]);
    }
    //修改所有库龄
    static public function updateSkuStockAgeAll(){
        $arr=Db::table('warehouse_country_cost')
            ->field('receipt_warehouse_id,date,surplus,sku')
            ->where(['status'=>1,'quantity'=>['>',0]])
            ->select();
        $receiptWarehouseIds=array_values(array_unique(array_column($arr,'receipt_warehouse_id')));
        $skus=array_values(array_unique(array_column($arr,'sku')));
        $warehouseCountryStock=Db::table('warehouse_country_stock')
            ->field('sku,receipt_warehouse_id,physical_stock')
            ->where(['receipt_warehouse_id'=>['in',$receiptWarehouseIds],'sku'=>['in',$skus]])
            ->select();
        ;
        $physicalStock=[];
        foreach ($warehouseCountryStock as $v1){
            $physicalStock[$v1['receipt_warehouse_id'].$v1['sku']]=$v1['physical_stock'];
        }
        $stockAge=[];
        foreach ($arr as $value){
            if(empty($physicalStock[$value['receipt_warehouse_id'].$value['sku']])){
                continue;
            }
            if(empty($stockAge[$value['receipt_warehouse_id'].'##'.$value['sku']])){
                $stockAge[$value['receipt_warehouse_id'].'##'.$value['sku']]=0;
            }
            $stockAge[$value['receipt_warehouse_id'].'##'.$value['sku']] = $stockAge[$value['receipt_warehouse_id'].'##'.$value['sku']]+round(($value['surplus'] / $physicalStock[$value['receipt_warehouse_id'].$value['sku']]) * ((time() - strtotime($value['date'])) / 86400), 4); // 库龄保留两位小数
        }
        $update=[];
        foreach ($stockAge as $k2=>$v2){
            $a=explode('##',$k2);
            if(empty($a[0])||empty($a[1])){
                continue;
            }
            $update[]=['receipt_warehouse_id'=>$a[0],'sku'=>$a[1],'stock_age'=>$v2];
        }
        !empty($update)&&ToolModel::dbInsertOrUpdate('warehouse_country_stock',$update);
        Db::table('warehouse_country_stock')
            ->where(['physical_stock'=>0])
            ->update(['stock_age'=>0]);
        return returnArr(1);
    }
}